<template>
  <div
    class="container"
    style="width: 100%; margin: 20px 40px"
    v-loading="loading"
  >
    <div v-if="showInfo == 0" align="center">
      <br />
      <h1>诊断专家组正在为您定制专属调研问卷,将请期待……</h1>
    </div>
    <div v-if="showInfo > 0">
      <!--    <el-button type="default" round size="medium " @click.native="handleOverview()" style="display: block;float: right;margin-right: 40px;position: relative;z-index: 1;">诊断进度   <i class="el-icon-right"/></el-button>-->
      <el-button
        type="default"
        round
        size="medium "
        @click.native="handleOverview()"
        style="
          display: block;
          float: right;
          margin-right: 40px;
          position: relative;
          z-index: 1;
        "
        >报告生成 <i class="el-icon-right"
      /></el-button>
      <el-button
        type="default"
        round
        size="medium "
        :loading="scoring"
        @click.native="handelAutoScoring()"
        style="
          display: block;
          float: right;
          margin-right: 40px;
          position: relative;
          z-index: 1;
        "
        >自动评分 <i class="el-icon-right"
      /></el-button>
      <el-row :gutter="20" :show-overflow-tooltip="true">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="domainName"
              placeholder="请输入领域名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container" style="min-width: 200px">
            <el-tree
              :data="domainOptions"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :default-expand-all="true"
              :auto-expand-parent="true"
              highlight-current:true
              node-key="id"
              ref="myTree"
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="10">
          <div style="clear: both">
            <el-form
              style="
                display: block;
                margin: 20px;
                float: none;
                text-align: left;
                max-width: 800px;
                z-index: 1;
              "
            >
              <problem-item
                v-for="(element, index) in drawingList"
                :key="element.renderKey"
                :drawing-list="drawingList"
                :element="element"
                :index="index"
                @handleDownload="handleDownload"
                @changeScore="changeScore"
                @setValue="setValue"
              />
            </el-form>
          </div>

          <div style="clear: both">
            <!--            <el-divider-->
            <!--              ><i class="el-icon-info">请在下方给出诊断意见</i></el-divider-->
            <!--            >-->
            <!--            <el-form>-->
            <!--              <el-form-item label="存在问题描述">-->
            <!--                <editor v-model="form.questionDesc" :min-height="192" :autofocus="false" />-->
            <!--              </el-form-item>-->
            <!--              <el-form-item label="诊断意见">-->
            <!--                <editor v-model="form.suggestion" :min-height="192" :autofocus="false" />-->
            <!--              </el-form-item>-->
            <!--              <el-form-item label="后续工作">-->
            <!--                <editor v-model="form.todo" :min-height="192"  :autofocus="false"/>-->
            <!--              </el-form-item>-->
            <!--            </el-form>-->

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import render from "@/utils/generator/render";
import logo from "@/assets/logo/logo.png";
import ProblemItem from "@/views/system/diagnosis/Recordtem";
import { treeselect2 } from "@/api/system/questiondomain";
import { getNaireQuestionsWithGrade } from "@/api/system/naire";

import { listRecord } from "@/api/system/diagnosisrecord";
import {
  autoScoring,
  batchAddDiagnosisdetail,
} from "@/api/system/diagnosisdetail";
import { genDiagnosisreport } from "@/api/system/diagnosisreport";

let oldActiveId;

export default {
  components: {
    render,
    ProblemItem,
  },
  data() {
    return {
      scoring: false,
      scores: new Map(),
      loading: false,
      showInfo: -1,
      activities: [],
      domainOptions: undefined,
      domainName: undefined,
      logo,
      idGlobal: 100,
      labelWidth: 100,
      drawingList: undefined,
      drawingData: {},
      activeId: null,
      drawerVisible: false,
      formData: {},
      dialogVisible: false,
      generateConf: null,
      showFileName: false,
      activeData: [],
      queryParams: {
        companyId: undefined,
        naireId: undefined,
        domain: 12,
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      form: {
        companyId: null,
        naireId: null,
        domainId: null,
        orderNum: 0,
        questionDesc: null,
        suggestion: null,
        todo: null,
        delFlag: 0,
      },
    };
  },
  created() {
    this.drawingList = [];
    if (this.$route.query.naireId)
      this.queryParams.naireId = this.$route.query.naireId;
    if (this.$route.query.domain)
      this.queryParams.domain = this.$route.query.domain;
    if (this.$route.query.companyId)
      this.queryParams.companyId = this.$route.query.companyId;

    this.getTreeselect();
    this.getQuestions();
    this.getDiagnosisRecord();
  },
  watch: {},

  methods: {
    recordScore() {
      let data = {};
      data.companyId = this.queryParams.companyId;
      data.naireId = this.queryParams.naireId;

      let obj = Object.create(null);
      for (let [k, v] of this.scores) {
        obj[k] = v;
      }
      data.scores = JSON.stringify(obj);
      batchAddDiagnosisdetail(data).then((response) => {
        this.$modal.msgSuccess("评分更新成功");
      });
    },
    getDiagnosisRecord() {
      this.loading = true;
      this.reset();

      this.form.companyId = this.queryParams.companyId;
      this.form.naireId = this.queryParams.naireId;
      this.form.domainId = this.queryParams.domain;
      // console.log("this.form", this.form);
      listRecord(this.form).then((response) => {
        this.recordList = response.rows;
        if (this.recordList.length > 0) {
          this.form.todo = this.recordList[0].todo;
          this.form.questionDesc = this.recordList[0].questionDesc;
          this.form.suggestion = this.recordList[0].suggestion;
        }
        // console.log("this.form", this.form);
        this.loading = false;
      });
    },
    getQuestions() {
      this.$route.meta.title = "调研问卷";
      this.loading = true;
      this.scores.clear();
      getNaireQuestionsWithGrade(this.queryParams).then((response) => {
        this.drawingList = [];
        let questions = response.data;
        for (let question of questions) {
          let tmp = JSON.parse(question.detail);
          tmp.questionId = question.questionId;
          tmp.show_other = false;
          tmp.show_history = false;
          tmp.show_history_btn = false;
          tmp.activities = this.activities;
          tmp.records = question.records;
          tmp.grade = question.grade;
          tmp.label = tmp.label + "（共" + question.score + "分）";
          this.scores.set(tmp.questionId, tmp.grade);

          if (question.records != null && question.records.length > 0) {
            tmp.defaultValue = JSON.parse(question.records[0].answer);
            tmp.show_history_btn = true;
            for (let record of question.records) {
              tmp.activities.push({
                content: record.createBy + "已回答此问题",
                timestamp: record.createTime,
              });
            }
          }

          this.drawingList.push(tmp);
        }
        this.showInfo = this.drawingList.length;

        this.loading = false;
      });
      this.loading = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.form.companyId = this.queryParams.companyId;
      this.form.naireId = this.queryParams.naireId;
      this.form.domainId = this.queryParams.domain;

      this.recordScore();
    },
    changeScore(questionId, score) {
      this.scores.set(questionId, score);
      console.log(" this.scores", this.scores);
    },
    reset() {
      this.form = {
        companyId: null,
        naireId: null,
        domainId: null,
        orderNum: 0,
        questionDesc: null,
        suggestion: null,
      };
    },
    getTreeselect() {
      treeselect2(this.queryParams.companyId, this.queryParams.naireId).then(
        (response) => {
          this.domainOptions = response.data;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (!data?.children) {
        this.queryParams.domain = data.id;
        this.handleQuery();
      }
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.getQuestions();
      this.getDiagnosisRecord();
    },
    handleOverview() {
      // this.$store.dispatch("tagsView/delView", this.$route);
      // this.$router.push({name: 'overviewStatus', query: {'naireId':this.queryParams.naireId}})
      this.form.companyId = this.queryParams.companyId;
      this.form.naireId = this.queryParams.naireId;
      genDiagnosisreport(this.form).then((response) => {
        this.$confirm("报告自动生成，请前往报告管理模块查看", "提示", {
          confirmButtonText: "前往",
          cancelButtonText: "取消",
          type: "success",
          center: true,
        })
          .then(() => {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({
              name: "diagnosisreportlist",
              query: {
                naireId: this.queryParams.naireId,
                companyId: this.queryParams.companyId,
              },
            });
          })
          .catch(() => {});
      });
    },
    handelAutoScoring() {
      // this.$store.dispatch("tagsView/delView", this.$route);
      // this.$router.push({name: 'overviewStatus', query: {'naireId':this.queryParams.naireId}})
      this.form.companyId = this.queryParams.companyId;
      this.form.naireId = this.queryParams.naireId;
      this.scoring = true;
      autoScoring(this.form).then((response) => {
        this.$modal.msgSuccess("自动评分成功");
        this.scoring = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    setValue(element, answer) {
      element.defaultValue = JSON.parse(answer);
    },
    handleDownload(filename) {
      console.log("start download", filename);
      window.location.href = process.env.VUE_APP_BASE_API + filename;
    },
  },
};
</script>

<style lang="scss">
body,
html {
  margin: 0;
  padding: 0;
  background: #fff;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial,
    sans-serif, Apple Color Emoji, Segoe UI Emoji;
}

input,
textarea {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial,
    sans-serif, Apple Color Emoji, Segoe UI Emoji;
}

.editor-tabs {
  background: #121315;

  .el-tabs__header {
    margin: 0;
    border-bottom-color: #121315;

    .el-tabs__nav {
      border-color: #121315;
    }
  }

  .el-tabs__item {
    height: 32px;
    line-height: 32px;
    color: #888a8e;
    border-left: 1px solid #121315 !important;
    background: #363636;
    margin-right: 5px;
    user-select: none;
  }

  .el-tabs__item.is-active {
    background: #1e1e1e;
    border-bottom-color: #1e1e1e !important;
    color: #fff;
  }

  .el-icon-edit {
    color: #f1fa8c;
  }

  .el-icon-document {
    color: #a95812;
  }
}

// home
.right-scrollbar {
  .el-scrollbar__view {
    padding: 12px 18px 15px 15px;
  }
}

.left-scrollbar .el-scrollbar__wrap {
  box-sizing: border-box;
  overflow-x: hidden !important;
  margin-bottom: 0 !important;
}

.center-tabs {
  .el-tabs__header {
    margin-bottom: 0 !important;
  }

  .el-tabs__item {
    width: 50%;
    text-align: center;
  }

  .el-tabs__nav {
    width: 100%;
  }
}

.reg-item {
  padding: 12px 6px;
  background: #f8f8f8;
  position: relative;
  border-radius: 4px;

  .close-btn {
    position: absolute;
    right: -6px;
    top: -6px;
    display: block;
    width: 16px;
    height: 16px;
    line-height: 16px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    color: #fff;
    text-align: center;
    z-index: 1;
    cursor: pointer;
    font-size: 12px;

    &:hover {
      background: rgba(210, 23, 23, 0.5);
    }
  }

  & + .reg-item {
    margin-top: 18px;
  }
}

.action-bar {
  & .el-button + .el-button {
    margin-left: 15px;
  }

  & i {
    font-size: 20px;
    vertical-align: middle;
    position: relative;
    top: -1px;
  }
}

.custom-tree-node {
  width: 100%;
  font-size: 14px;

  .node-operation {
    float: right;
  }

  i[class*="el-icon"] + i[class*="el-icon"] {
    margin-left: 6px;
  }

  .el-icon-plus {
    color: #409eff;
  }

  .el-icon-delete {
    color: #157a0c;
  }
}

.left-scrollbar .el-scrollbar__view {
  overflow-x: hidden;
}

.el-rate {
  display: inline-block;
  vertical-align: text-top;
}

.el-upload__tip {
  line-height: 1.2;
}

$selectedColor: #f6f7ff;
$lighterBlue: #409eff;

.container {
  position: relative;
  width: 100%;
  height: 100%;
}

.components-list {
  padding: 8px;
  box-sizing: border-box;
  height: 100%;

  .components-item {
    display: inline-block;
    width: 48%;
    margin: 1%;
    transition: transform 0ms !important;
  }
}

.components-draggable {
  padding-bottom: 20px;
}

.components-title {
  font-size: 14px;
  color: #222;
  margin: 6px 2px;

  .svg-icon {
    color: #666;
    font-size: 18px;
  }
}

.components-body {
  padding: 8px 10px;
  background: $selectedColor;
  font-size: 12px;
  cursor: move;
  border: 1px dashed $selectedColor;
  border-radius: 3px;

  .svg-icon {
    color: #777;
    font-size: 15px;
  }

  &:hover {
    border: 1px dashed #787be8;
    color: #787be8;

    .svg-icon {
      color: #787be8;
    }
  }
}

.left-board {
  width: 260px;
  position: absolute;
  left: 0;
  top: 0;
  height: 100vh;
}

.left-scrollbar {
  height: calc(100vh - 42px);
  overflow: hidden;
}

.center-scrollbar {
  height: calc(100vh - 42px);
  overflow: hidden;
  border-left: 1px solid #f1e8e8;
  border-right: 1px solid #f1e8e8;
  box-sizing: border-box;
}

.center-board {
  height: 100vh;
  width: auto;
  margin: 0 350px 0 260px;
  box-sizing: border-box;
}

.empty-info {
  position: absolute;
  top: 46%;
  left: 0;
  right: 0;
  text-align: center;
  font-size: 18px;
  color: #ccb1ea;
  letter-spacing: 4px;
}

.action-bar {
  position: relative;
  height: 42px;
  text-align: right;
  padding: 0 15px;
  box-sizing: border-box;
  border: 1px solid #f1e8e8;
  border-top: none;
  border-left: none;

  .delete-btn {
    color: #f56c6c;
  }
}

.logo-wrapper {
  position: relative;
  height: 42px;
  background: #fff;
  border-bottom: 1px solid #f1e8e8;
  box-sizing: border-box;
}

.logo {
  position: absolute;
  left: 12px;
  top: 6px;
  line-height: 30px;
  color: #00afff;
  font-weight: 600;
  font-size: 17px;
  white-space: nowrap;

  > img {
    width: 30px;
    height: 30px;
    vertical-align: top;
  }

  .github {
    display: inline-block;
    vertical-align: sub;
    margin-left: 15px;

    > img {
      height: 22px;
    }
  }
}

.center-board-row {
  padding: 12px 12px 15px 12px;
  box-sizing: border-box;

  & > .el-form {
    // 69 = 12+15+42
    height: calc(100vh - 69px);
  }
}

.drawing-board {
  height: 100%;
  position: relative;

  .components-body {
    padding: 0;
    margin: 0;
    font-size: 0;
  }

  .sortable-ghost {
    position: relative;
    display: block;
    overflow: hidden;

    &::before {
      content: " ";
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      height: 3px;
      background: rgb(89, 89, 223);
      z-index: 2;
    }
  }

  .components-item.sortable-ghost {
    width: 100%;
    height: 60px;
    background-color: $selectedColor;
  }

  .active-from-item {
    & > .el-form-item {
      background: $selectedColor;
      border-radius: 6px;
    }

    & > .drawing-item-copy,
    & > .drawing-item-delete {
      display: initial;
    }

    & > .component-name {
      color: $lighterBlue;
    }
  }

  .el-form-item {
    margin-bottom: 15px;
  }
}

.drawing-item {
  position: relative;
  cursor: move;

  &.unfocus-bordered:not(.activeFromItem) > div:first-child {
    border: 1px dashed #ccc;
  }

  .el-form-item {
    padding: 12px 10px;
  }
}

.drawing-row-item {
  position: relative;
  cursor: move;
  box-sizing: border-box;
  border: 1px dashed #ccc;
  border-radius: 3px;
  padding: 0 2px;
  margin-bottom: 15px;

  .drawing-row-item {
    margin-bottom: 2px;
  }

  .el-col {
    margin-top: 22px;
  }

  .el-form-item {
    margin-bottom: 0;
  }

  .drag-wrapper {
    min-height: 80px;
  }

  &.active-from-item {
    border: 1px dashed $lighterBlue;
  }

  .component-name {
    position: absolute;
    top: 0;
    left: 0;
    font-size: 12px;
    color: #bbb;
    display: inline-block;
    padding: 0 6px;
  }
}

.drawing-item,
.drawing-row-item {
  &:hover {
    & > .el-form-item {
      background: $selectedColor;
      border-radius: 6px;
    }

    & > .drawing-item-copy,
    & > .drawing-item-delete {
      display: initial;
    }
  }

  & > .drawing-item-copy,
  & > .drawing-item-delete {
    display: none;
    position: absolute;
    top: -10px;
    width: 22px;
    height: 22px;
    line-height: 22px;
    text-align: center;
    border-radius: 50%;
    font-size: 12px;
    border: 1px solid;
    cursor: pointer;
    z-index: 1;
  }

  & > .drawing-item-copy {
    right: 56px;
    border-color: $lighterBlue;
    color: $lighterBlue;
    background: #fff;

    &:hover {
      background: $lighterBlue;
      color: #fff;
    }
  }

  & > .drawing-item-delete {
    right: 24px;
    border-color: #f56c6c;
    color: #f56c6c;
    background: #fff;

    &:hover {
      background: #f56c6c;
      color: #fff;
    }
  }
}
</style>
